<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}`"
    width="960"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div class="h-[460px]">
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
        :originOption="optionsData"
      >
        <template #weightCalc="{ value, input }">
          <WeightCalc
            :value="value"
            @input="input"
            :optionsData="optionsData"
          />
        </template>
        <template #currency="{ value, input }">
          <CurrencySelect @update:model-value="input" :model-value="value" />
        </template>
        <template #priceCalc="{ value, input }">
          <PriceCalc :value="value" @input="input" :optionsData="optionsData" />
        </template>
        <template #tax_rate="{ value, input }">
          <div class="flex items-center">
            <span class="mr-[4px] whitespace-nowrap">设置税率为</span>
            <el-input-number
              :min="0"
              :max="100"
              :controls="false"
              style="width: 100px"
              :modelValue="value"
              placeholder="请输入"
              @input="input"
            ></el-input-number>
            <div class="ml-[8px] flex items-center">
              <!-- <i class="shrink-0 iconfont icon-hint_line"></i> -->
               <svg-icon
        icon-class="hint_line"
      />
              <span class="text-[12px] text-[#999] leading-[17px]">
                税费的计算为：系统申报价值*税率（不同国家税率不同），这个得到的值，放入订单，算入派送费用的申报的税费
              </span>
            </div>
          </div>
        </template>
      </VForm>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import VForm from "@/components/Form/index.vue";
import CurrencySelect from "@/components/CurrencySelect/index.vue";

import PriceCalc from "./PriceCalc/index.vue";
import WeightCalc from "./WeightCalc/index.vue";

import { createDetail, updateDetail } from "../../api/index";

const props = defineProps({
  declare_rules_id: { type: [String, Number], default: "" },
  value: { type: Object, default: () => ({}) },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  optionsData: { type: Object, default: () => ({}) },
  useReq: { type: Boolean, default: false },
});

const emit = defineEmits([
  "update:modelValue",
  "refresh",
  "close",
  "add",
  "edit",
]);

const formOption = {
  labelPosition: "top",
  inline: true,
};

const checkPriceCalc = async (rule, value, callback) => {
  const {
    radio,
    price,
    priceType,
    hasMin,
    hasMax,
    minVal,
    maxVal,
    pricePercent,
  } = value || {};
  if (+radio === 0 && price !== 0 && !price) {
    return callback(new Error("请输入固定价格"));
  }
  if (+radio === 1) {
    if (!priceType) {
      return callback(new Error("请选择金额类型"));
    }
    if (!pricePercent) {
      return callback(new Error("请输入金额占比"));
    }
    if (hasMin && !minVal) {
      return callback(new Error("请输入最低价格"));
    }
    if (hasMax && !maxVal) {
      return callback(new Error("请输入最高价格"));
    }
  }
};

const checkWeightCalc = async (rule, value, callback) => {
  const { radio, weight, weightType, hasMin, hasMax, minVal, maxVal } =
    value || {};
  if (+radio === 0 && weight !== 0 && !weight) {
    return callback(new Error("请输入固定重量"));
  }
  if (+radio === 1) {
    if (!weightType) {
      return callback(new Error("请选择重量类型"));
    }
    if (hasMin && !minVal) {
      return callback(new Error("请输入最低价格"));
    }
    if (hasMax && !maxVal) {
      return callback(new Error("请输入最高价格"));
    }
  }
};

const rules = {
  destination_country: [
    { required: true, message: "请选择目的国家", trigger: "blur" },
  ],
  priceCalc: [{ required: true, validator: checkPriceCalc, trigger: "change" }],
  weightCalc: [
    { required: true, validator: checkWeightCalc, trigger: "change" },
  ],
};

const form = ref();
const model = ref({});
const loading = ref();

const fieldList = [
  { label: "基础信息", type: "title" },
  {
    field: "destination_country",
    label: "目的国家",
    type: "select",
    multiple: true,
    originField: "mapCountry",
    style: { width: "420px" },
    options: {
      valueKey: "country",
      labelKey: "country_name",
    },
  },
  {
    field: "currency",
    slot: "currency",
    label: "申报币种",
    style: { width: "180px" },
  },
  {
    field: "weightCalc",
    label: "申报重量的计算方法",
    slot: "weightCalc",
  },
  {
    field: "priceCalc",
    label: "申报价格的计算方法",
    slot: "priceCalc",
  },
  {
    field: "tax_rate",
    label: "预估申报税率设置",
    slot: "tax_rate",
  },
  {
    field: "declare_link_type",
    label: "报关链接",
    type: "select",
    originField: "declare_link_type",
    default: `<div class="flex items-center ml-[4px]">
      <svg-icon icon-class="hint_line"/>
      <span class="text-[12px] leading-[17px] text-[#999]">物流预申报时，向物流供应商发送的产品展示链接方式</span>
    </div>`,
  },
];

watch(
  () => props.value,
  (val) => {
    if (val) {
      model.value = val;
    }
  }
);

const isEdit = computed(() => {
  return !!props.value?.id;
});

const handleSave = async () => {
  try {
    const formInfo = await form.value.submit();
    const { weightCalc = {}, priceCalc = {} } = formInfo;
    const params = {
      ...formInfo,
      weight_calc: weightCalc?.radio,
      weight_type: weightCalc?.weightType,
      fixed_weight: weightCalc?.weight,
      min_weight: weightCalc?.minVal||0,
      max_weight: weightCalc?.maxVal||0,
      price_calc: priceCalc?.radio,
      price_type: priceCalc?.priceType,
      price_percent: priceCalc?.pricePercent,
      fixed_price: priceCalc.price,
      min_price: priceCalc?.minVal||0,
      max_price: priceCalc?.maxVal||0,
    };

    delete params.priceCalc;
    delete params.weightCalc;

    const { value: { id } = { id: "" }, useReq, declare_rules_id } = props;

    if (useReq) {
      const api = {
        edit: updateDetail,
        add: createDetail,
      };

      const { code, message } = await api[isEdit.value ? "edit" : "add"]({
        id: id || undefined,
        declare_rules_id: declare_rules_id || undefined,
        ...params,
      });
      if (code !== 200) {
        ElMessage.warning(message);
        return;
      }
      ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
      handleClose(true);
      return;
    }

    emit(Object.keys(props?.value)?.length ? "edit" : "add", params);
    handleClose();
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const handleClose = async (refresh) => {
  model.value = {};
  await nextTick();
  form.value.resetForm();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
